﻿//全局路由分配
var tpljs;//设置全局模板
var isAPP=navigator.userAgent.match(/Html5Plus/i);
var uss = navigator.userAgent;
var isAndroid = uss.indexOf('Android') > -1 || uss.indexOf('Adr') > -1; //android终端
var isiOS = !!uss.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
var ossroot="https://foodievc.oss-ap-southeast-1.aliyuncs.com/";
function main(){

	if(mainfalse) return false;
	maintrue=true;

	tpljs=$(tplhtml);//设置全局模板
	var mem_id = getCookie("yingsoft_home_member_id");
    mem_id == "null" ? mem_id = 0 : 0;
    //设置默认语言

    var setlane=getCookie("language");
    lange = typeof tpljson[setlane]=="string"? JSON.parse(tpljson[setlane]):tpljson[setlane];

	 //设置全局路由
    Q.reg('main', function (aid) {
	    var route = window.location.hash.slice(2),
	    type = 0,
	    can = route.split("?")[1],
	    route = route.split("?")[0];
	    if(route == "")
	    {
	    return false;
	    }
	    var timestamp = Date.parse(new Date());
	    var addcan = can != undefined ? "&" + can : '';
	    ajax_new(route, type, route);
	});
	Q.init({
	    index: 'main'
	});
	
	
	
	//初始化
//	if(getUrlParam2("from")=="app" || getCookie("from")=="app"){
//		setCookie("from","app",300)
//		$("html").addClass("app")
//	}
	
	//getCookie("from")=="app";
	delCookie("from")
	
	if(getUrlParam2("from")=="app"){
		Q.go("404-html");
	}else if(window.location.hash==""){
		Q.go("root-html");
	}
	
	
	
   
    //设置websocket
    //
	if(localStorage.getItem("key1")!=null&&connect_b){
		if(setUI()){//判断是否为点餐界面
			connect();
		};		
	}
	//ISO去除延迟
	FastClick.attach(document.body);
}
//判断是否为点餐界面
function setUI(){
	if($(".root-html").length>0 || $(".select-html").length>0 || $(".order_see-html").length>0 || $(".changing-html").length>0 || $(".finish-html").length>0 || $(".lose-html").length>0){
		return true;
	}else{
		return false;
	}
}

//加载小动画
function addgwc(e) {
      var $th = e;
    ////获取开始点坐标
    ////ev.target ====>
    var wint = $(window).scrollTop();
    var startOffset = $th.offset();
    ////获取结束点坐标
    var endTop = window.innerHeight - 60, endLeft = $("#icon_gw").offset().left + 20, left = startOffset.left, top = startOffset.top - wint;
    var $pointDiv = $('<div class="point-pre point-outer" style="left:' + left + 'px; top:' + top + 'px;"><div class="point-inner"></div></div>').appendTo("body")
    var outer = $pointDiv
    var inner = outer.find(".point-inner");
    setTimeout(function () {
        outer[0].style.webkitTransform = 'translate3d(0,' + (endTop - top) + 'px,0)';
        inner[0].style.webkitTransform = 'translate3d(' + (endLeft - left) + 'px,0,0)';
        outer.one('webkitTransitionEnd mozTransitionEnd MSTransitionEnd otransitionend transitionend', function () {
            outer.remove();
            $('#icon_gw').addClass('tada1 animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                $(this).removeClass("animated").removeClass("tada1");
            });
        });
        setTimeout(function () {
            outer.remove();
            $('#icon_gw').addClass('tada1 animated');
            setTimeout(function () {
                $('#icon_gw').removeClass("animated").removeClass("tada1");
            }, 900)
        }, 900)
    }, 10);
}

//返回匹配的json对象
function getjsons(obj,id,ke){
	var s={};
	$.each(obj, function(i,v) {
		if(v[ke]==id){
			s=v;
			return false;
		}
	});
	return s;
}
//返回匹配的json对象的索引
function getindex(obj,id,ke){
	var s=-1;
	$.each(obj, function(i,v) {
		
		if(v[ke]==id){
			s=i;
			return false;
		}
	});

	return s;
}
//返回匹配的json对象
function getjsons2(obj,id,ke,id2,ke2){
	var s={};
	$.each(obj, function(i,v) {
		if(v[ke]==id && v[ke2]==id2){
			s=v;
			return false;
		}
	});
	return s;
}
//返回匹配的json对象的索引
function getindex2(obj,id,ke,id2,ke2){
	var s=-1;
	$.each(obj, function(i,v) {
		if(v[ke]==id && v[ke2]==id2){
			s=i;
			return false;
		}
	});
	return s;
}

var connect_b=true;//判断是否调用websookid
//全局已选对象
var select_obj = null,
	caidan_json = null,
	guige1_json = null,
	kouwei1_json = null,
	peicai_json = null;
	//设置菜品
	if(localStorage.getItem("key2") !=null)  caidan_json=JSON.parse(localStorage.getItem("key2"));
	if(localStorage.getItem("key3") !=null)  guige1_json=JSON.parse(localStorage.getItem("key3"));
	if(localStorage.getItem("key4") !=null)  kouwei1_json=JSON.parse(localStorage.getItem("key4"));
	if(localStorage.getItem("key5") !=null)  peicai_json=JSON.parse(localStorage.getItem("key5"));

//语言选择设置
var setlanges=[{ title: "Melayu",value: "ms",},{ title: "English",value: "en",},{ title: "简体中文",value: "zh",}]

var cart_obj = {
    "title":'',
    "total": 0,
    "my_number": 0,
    "my_number_1": 0,
    "my_list": new Array(),
    "th_number": 0,
    "th_number_1": 0,
    "th_list": new Array()
};
//匹配

//添加到购物车
var setgouwu=setTimeout(function(){},10),
	resnum=0;
	
$(document).on("click","#menu-right .p",function(){
	setClick($(this));
})
$(document).on("click","#menu-right .item .w",function(){
	if($(this).parent().hasClass("disable")) return false;
	
	var $th=$(this),
		$thnum=$th.parent().find(".addright").attr("data-num");
		//alert($thnum)
		if($thnum==0){
			$th.parent().find(".addright .p.p2").click();
		}
})
//添加到购物车
function setClick(obj,s2) {
    var $th=obj,
        $thp = $th.parent(),
        $spec = $thp.hasClass("spec"),
        $nullspec = $thp.hasClass("nullspec"),
        parid = $thp.attr("data-parent-id"),
        id = $thp.attr("data-id"),//菜品ID
        price = $thp.attr("data-price"),//单价
        specid = $thp.attr("data-specid"),//规格
        cartid = $thp.attr("data-cart_id"),//购物车
        garnishid = $thp.attr("data-garnish_id") || 0,//规格
        num = $thp.attr("data-num") || 0,//以选数量
		$t_index=$thp.parents(".item").attr("data-index"),//当前选择索引
		$t_p_index=$thp.parents(".item").attr("data-parentindex");//父级索引
		//判断是否套餐
		if($thp.hasClass("taocan")){
			console.log(select_obj)
			console.log($t_p_index,$t_index)
			var newtaocan=select_obj[$t_p_index].goods_list[$t_index];
				console.log("套餐选择",newtaocan)
				pack_box.start(newtaocan)
			return false;
		}
		//套餐
		
		if($th.hasClass("disable")) return false;
		//有多规格的进入if
		if($spec){	
			
			if($nullspec){
				//没有多规格
				var ns0=num
				if ($th.hasClass("p2"))
		        {
		            ns0++;
		            addgwc($th)
		        }else
		        {
		            ns0--;
		            ns0<0?ns0=0:0;
		        }
		        //第一次添加购物车id
				if(num==0&&ns0==1){
					if ($th.hasClass("p2"))
		        	{
						var ndata=new Date().getTime().toString();   		
						var cart="1"+ndata.substring(5,ndata.length-1) + Math.floor(Math.random()*100000)
						
						var data={"cart_id": cart ,"member_id": getCookie("yingsoft_home_member_id"), "count":ns0,"goods_cate_id": parid, "goods_id": id, "taste_id": 0,"spec_id": 0,"status":1,"goods_price":price ,total_price: price,"remarks": "","is_pack":0,"is_wait":0,"is_give":0,"is_old":0,"cookbook":localStorage.getItem("cookbook")};
						//console.log(data)
						marry_fun(data);
					}
				}else{
					if(ns0==0){
						$thp.attr("data-cart_id","");
						var ojs1=$("#menu-right .item[data-id="+ id +"]");
						ojs1.find(".g3").text(0);
						ojs1.find(".addright").attr("data-num", 0);
						ojs1.removeClass("add")
						
						//删除最后一个
//						global_ajax(jsonpath + "put_set_cart", {"cart_id": cartid,"garnish_id": 0,"count": 0 }, function (e) {
//				       		
//				        //console.log(e);
//				    	})
						
					}
						 //{"cart_id": cartid,"garnish_id": garnishid,"count": num }
					    var adds=getjsons(cart_obj.my_list[getCookie("yingsoft_home_member_id")],cartid,'cart_id'),
					    pri=0;
					    if(garnishid==0)
					    {
					    	adds.count=ns0;
					    }
					        //console.log(adds)
					        if(!!adds.garnish_ids){
						    	$.each(adds.garnish_ids, function(i,v) {
						    		if(v.garnish_id==garnishid){
						    			v.count=ns0;
						    			
						    			if(v.count==0) {
						    				adds.garnish_ids.baoremove(i);
						    			}
						    		} 
						    		//console.log(v.count,v.goods_price,adds.count)
						    		pri+=accMul(accMul(v.count,v.goods_price),adds.count) 
						    	});
					    	}
					    //console.log(adds)	
					    
					    pri+=accMul(adds.count,adds.goods_price)
					    adds.total_price=toFixed2(pri,2);
					
					    marry_fun(adds);
				}
				
			}else{
				//多规格加减
				if ($th.hasClass("p2"))
		        {
		        	//判断是否分布点餐
		        	//addspec({"id": id, "parid": parid, "price": price })
		            if(localStorage.getItem("fenbu_diancan")=="1"){
		            	addspec_buzhou({"id": id, "parid": parid, "price": price })
		            }else{
		            	addspec({"id": id, "parid": parid, "price": price })
		            }
		        }else
		        {
		            $thp.find(".specem").show();
		            setTimeout(function(){
		            	$thp.find(".specem").hide();
		            },2000)
		        }
			}
			return false;
		}
		
        

        if ($th.hasClass("p2"))
        {
            num++;
        }else
        {
            num--;
            num<0?num=0:0;
            if(num==0){
            	$thp.parents(".item-l").remove()
            }
        }
       	
       	
       	 //{"cart_id": cartid,"garnish_id": garnishid,"count": num }
	    var adds=getjsons(cart_obj.my_list[getCookie("yingsoft_home_member_id")],cartid,'cart_id'),
	    pri=0;
	    if(garnishid==0)
	    {
	    	adds.count=num;
	    }
	        //console.log(adds)
	        if(!!adds.garnish_ids){
		    	$.each(adds.garnish_ids, function(i,v) {
		    		if(v.garnish_id==garnishid){
		    			v.count=num;
		    			if(v.count==0) {
		    				adds.garnish_ids.baoremove(i);
		    			}
		    		} 
		    		//console.log(v.count,v.goods_price,adds.count)
		    		pri+=accMul(accMul(v.count,v.goods_price),adds.count) 
		    	});
	    	}
	    //console.log(adds)	
	    
	    pri+=accMul(adds.count,adds.goods_price)
	    adds.total_price=toFixed2(pri,2);
	
	    marry_fun(adds);
	
}



//弹出规格选择
function addspec(obj,cartID){
	var obj=obj,
		menuobj=JSON.parse(localStorage.getItem("key1")),
		specjson={};
		specjson["spec"]=caidan_json[obj.id].spec_list
		$.each(specjson["spec"], function(i,v) {
			v["goods_spec_name"]=guige1_json[v.spec_id].goods_spec_name
		});
		specjson["garnish"]=caidan_json[obj.id].garnish_list;
		$.each(specjson["garnish"], function(i,v) {
			v["goods_garnish_name"]=peicai_json[v.garnish_id].goods_garnish_name
		});
		specjson["taste"]=caidan_json[obj.id].taste_list;
		$.each(specjson["taste"], function(i,v) {
			v["goods_taste_name"]=kouwei1_json[v.taste_id].goods_taste_name
		});
		specjson["name"]=caidan_json[obj.id].goods_name
		
		//设置原始单价
		//obj["price"]=caidan_json[obj.id].goods_price
		if(caidan_json[obj.id].goods_price_d){
			obj["price"]=caidan_json[obj.id].goods_price_d
		}else{
			obj["price"]=caidan_json[obj.id].goods_price
		}
		
		specjson["price"]=obj["price"]
	
	//console.log(specjson)
	
	$("#putong_guige").addClass("open").html(template("guige-js", specjson));
	setlange_obj()//设置前端语言
	var gbox=$("#putong_guige .g-box"),
	gboxh=gbox.find(".w").height();
	gbox.css({"margin-top":-(gboxh/2)});
	
	//修改菜品
	if(cartID){
		
		var cartobj=getjsons(cart_obj.my_list[getCookie("yingsoft_home_member_id")],cartID,"cart_id")

		//console.log(cartobj)
		$(".addright_s").attr("data-count",cartobj.count)
		$(".addright_s .g3").text(cartobj.count)
		if(!!cartobj.garnish_ids){
		$.each(cartobj.garnish_ids, function(i,v) {
			var jb=$(".guige-peicai-list a[data-id='"+v.garnish_id+"']");
			jb.addClass("on").attr("data-count",v.count).find("em").text(v.count)			
		});
		}
		
		$("#guige-box1 a[data-id='"+cartobj.spec_id+"']").addClass("on").siblings().removeClass("on")
		$("#guige-box2 a[data-id='"+cartobj.taste_id+"']").addClass("on").siblings().removeClass("on")
		$(".total_price").text(cartobj.total_price)
		
		//其他设置

	}
	

	//切换
	$("#guige-box1 dd a,#guige-box2 dd a").click(function(){
		$th=$(this);
		$th.addClass("on").siblings().removeClass("on")
		guigeset()
	})
	


	//总份数加减
	$(".addright_s .p1,.addright_s .p2").click(function(){
		var $t=$(this)
			$thp=$t.parent()
		if($t.hasClass("disable")) return false;
		var num = $thp.attr("data-count") != undefined ? $thp.attr("data-count") : 1;//以选数量

        if ($t.hasClass("p2"))
        {
            num++;
        }else
        {
            num--;
            num<0?num=0:0;
        }
      	if(num==1){
   			$thp.find(".p1").addClass("disable")
        }else{
        	$thp.find(".p1").removeClass("disable")
        }
        $thp.attr("data-count",num).find(".g3").text(num);
		guigeset()//计算价格
	})
	
	//添加配菜
	var garnish_max_count=caidan_json[obj.id].garnish_max_count
	$(".guige-box3 a").on("click",function(){
		var $th=$(this),	
			$th_ID=$th.attr("data-id"),
			$th_price=$th.attr("data-price"),
			$th_name=$th.attr("data-name");

		if($th.hasClass("on"))
		{
			var $th_num=$th.attr("data-count");			
			var html1 = '<div class="peiliaoadd  fiex cf" data-num="' + $th.attr("data-count") + '">';
                html1+='<div class="p p1 fiex1"><i></i><svg class="g1" ><use xlink:href="#f_4"></use></svg></div>';
                html1+='<span class="  fiex1"><span class="g3 f-32">' + $th.attr("data-count") + '</span></span>';
                html1+='<div class="p p2 fiex1"><i></i><svg class="g2" ><use xlink:href="#f_5"></use></svg></div>';
                html1+='</div>';

                 $.modal({
                    title: $th_name,
                    text: "<p class='dp-1 red'>" + $th_price + "</p><div class='dp-2 mag-t-20 pad-b-20 pad-r-40 pad-l-40'>" + html1 + "</div>",
                    buttons: [
                      { text: "<span class='aaa'>"+ lange["1062"] +"</span>", onClick: function () {
                             
							$th.find("em").text(1)
							$th.attr("data-count",1);
							$th.removeClass("on");
							guigeset()
                        }},
                      {
                          text: lange["1016"], onClick: function () {
							if($th_num==0) {
								$th.find("em").text(1)
								$th.attr("data-count",1);
								$th.removeClass("on");
							}else{
								$th.find("em").text($th_num)
								$th.attr("data-count",$th_num);
							}
							guigeset();                             
                          }
                      }
                    ]
                });
				var currgarnish=getjsons(caidan_json[obj.id].garnish_list,$th_ID,"garnish_id")//获取当前配菜对象
				console.log(currgarnish)
				//数量减
				setTimeout(function(){
					var $pei=$(".peiliaoadd")
					//console.log($pei)
					$(".peiliaoadd .p1").on("click",function(){
						if($pei.hasClass("null0")) return false;
						$th_num--;
						$pei.removeClass("null1");
						$pei.nextUntil().remove();//删除跟随元素
						if($th_num<=0) {
							$th_num=0;
							$pei.addClass("null0")
						};
						$pei.find(".g3").text($th_num);
					})
					//数量加
					$(".peiliaoadd .p2").on("click",function(){
						if($pei.hasClass("null1")) return false;
						$th_num++;
						$pei.removeClass("null0")
						if(currgarnish.maxcount){//如果有maxcount字段
							if(currgarnish.maxcount!=0 && $th_num>Math.floor(currgarnish.maxcount)){
								$th_num=Math.floor(currgarnish.maxcount);
								$pei.after('<div class="red mag-t-40 sss">'+ lange[1262] +' ['+$th_num+']</div>')
								$pei.addClass("null1")
							}
						}
						$pei.find(".g3").text($th_num);
					})
				},0)
			
		}else{
			
			//最大数量限制
			if(garnish_max_count==$th.parent().find(".on").length && garnish_max_count!=0){	
				$.toast(lange[1261]+"  [ "+garnish_max_count+" ]","text")
				return false;
			}
			//最大限制end
			
			$th.attr("data-count",1);
			$th.addClass("on");
			guigeset()
		}
		
	})

	
	//计算价格
	var price=0,//总价
		price_one=0;//单价
	function guigeset(){
			price=0;
		var specprice=$("#guige-box1 a.on").attr("data-price");
			if(!!specprice){
				price=accAdd(price , specprice)
			}else{
				price=obj.price;
			}	
			
		var tasteprice=$("#guige-box2 a.on").attr("data-price");
			
		    if(!!tasteprice){
				price=accAdd(price , tasteprice)
			};	
		    $("#guige-box3 dd a").each(function(){
				var $t=$(this),
					$tprice=$t.attr("data-price"),
					$tcount=$t.attr("data-count");
				if($t.hasClass("on")){
					var sp=accMul($tprice, $tcount) 
					price=accAdd(price,sp)
				}
			})
		    //console.log(price)
		    var ss=$("#addright_s").attr("data-count");
		    price_one=price;
		    price=toFixed2(accMul(price, ss),2)
		    $("#pirce_b").text(price)
	}
	guigeset()//计算价格
	
	//选择
	var fenpeitrue=false;//是否同意分配数据
	$(".guige-box .bon-red").click(function(){
		var specid=$(".guige-box1 a.on").attr("data-id") || 0,
		    tasteid=$(".guige-box2 a.on").attr("data-id") || 0,
		    stnum=$(".addright_s").attr("data-count");
		var grn=[];
			$(".guige-peicai-list a").each(function(){
				var $t=$(this),
					$tid=$t.attr("data-id"),
					$tcount=$t.attr("data-count"),
					$tprice=$t.attr("data-price");
				if($t.hasClass("on")){
					grn.push({"garnish_id":$tid,"count":$tcount,"goods_price":$tprice});
				}
			})
		
		//console.log(caidan_json[obj.id].is_prompt!=0)
		if(!fenpeitrue && stnum>1 && caidan_json[obj.id].is_prompt==1){
		//多份提示 分配数量
		var htmljiajin=function(ind,e){
			var ss='<dl class="cf"><dt>No.'+ind+'</dt><dd class="cf"><div class="fr">份</div><div class="oh fiex">'
				ss+='<div class="fiex1 jian"><svg class="g1"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#f_4"></use></svg></div>'
				ss+='<div class="fiex1"><span class="num">'+ e +'</span></div>'
				ss+='<div class="fiex1 jia"><svg class="g2"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#f_5"></use></svg></div>'
				ss+='</div></dd></dl>';
			return ss;				
		}
		
		var bons=stnum<12?stnum:12;
		var jl={};//记录分配数量数组
		var html1="<div class='cf fenpei-box'>";
			html1+="<div class='t cf' id='fenpeia'><div class='pad-t-20 t1 center f-28 c999'>"+lange["1154"]+"</div><div class='t2'>";	
			for(var i=1;i<=bons;i++){
				if(i==1){	
					html1+="<span class='on'>"+ i +"</span>";
				}else{
					html1+="<span>"+ i +"</span>";
				}						
			}			
			html1+="</div></div>";
			html1+="<div class='mag-t-20 center f-28 c999'>"+lange["1153"]+"("+stnum+")</div><div class='list' id='fenpeilist'>";
			html1+=htmljiajin(1,stnum)			
			html1+="</div>";
			html1+="</div>";
			
		   $.modal({
                    title: lange["1151"],
                    text: html1,
                    buttons: [
                      { text: "<span class='aaa'>"+lange["1152"]+"</span>", onClick: function () {
                             fenpeitrue=true;
                             $(".guige-box .bon-red").click();
                        }},
                      {
                          text: lange["1016"], onClick: function () {
                          	addgwc($(".guige-box .b .bon-red"));
							
                          	$.each(jl, function(i,v) {
                          		var num=v;
                          		var pir=toFixed2(accMul(price_one, num),2)
                          		
                          		var ndata=new Date().getTime().toString();   		
							    var cart="1"+ndata.substring(5,ndata.length-1) + Math.floor(Math.random()*1000000)
							    
								var data={"cart_id": cart ,"member_id": getCookie("yingsoft_home_member_id"), "count":num,"goods_cate_id": obj.parid, "goods_id": obj.id, "taste_id": tasteid,"spec_id": specid,"garnish_ids":grn,"status":1,"goods_price":obj.price ,total_price: pir,"remarks": "","is_pack":0,"is_wait":0,"is_give":0,"is_old":0,"cookbook":localStorage.getItem("cookbook")};		
								
								marry_fun(data);   
								$(".guige").html("").removeClass("open");
                          	});                          	
							
							    
                          }
                      }
                    ]
                });

			$("#fenpeia .t2 span").on("click",function(){
				var html2="",
					inds=$(this).text(),
					qms=stnum%inds,//取模数
					jss=stnum-qms,//实际计算书
					ncs=jss/inds;//除数
					for(var i=0;i<inds;i++){						
						if(i<qms){								
							html2+=htmljiajin(i+1,ncs+1)
						}else{
							html2+=htmljiajin(i+1,ncs)
						}						
					}					
					$("#fenpeilist").html(html2);
					jl=[];
					$("#fenpeilist dl").each(function(e){
						var num=$(this).find(".num").text();
						jl[e]=num
					});
					
					//设置弹出框位置
					var weheight=$(".weui-dialog--visible").height()
					$(".weui-dialog--visible").css({"top":($(window).height()-weheight)/2})
					
				$(this).addClass("on").siblings().removeClass("on");
				
				$("#fenpeilist .jia,#fenpeilist .jian").on("click",function(){
					
					var $th=$(this),
						nums=$th.parent().find(".num").text();
					if($th.hasClass("jian")){
						nums--;
						nums<1?nums=1:0;					
					}else{
						nums++;
					}

					$th.parent().find(".num").text(nums);
					//重置选择数组
					jl=[];
					$("#fenpeilist dl").each(function(e){
						var num=$(this).find(".num").text();
						jl[e]=num
					})
				});	
					
			});
			$("#fenpeia .t2 span.on").click();
					
		//end
		return false;
		}
		
		addgwc($(this));
		$(".select_article").hide().removeClass("open");
		//增加数量

		
		var ndata=new Date().getTime().toString();   		
		var cart="1"+ndata.substring(5,ndata.length-1) + Math.floor(Math.random()*1000000)
		var data={"cart_id": cart ,"member_id": getCookie("yingsoft_home_member_id"), "count":stnum,"goods_cate_id": obj.parid, "goods_id": obj.id, "taste_id": tasteid,"spec_id": specid,"garnish_ids":grn,"status":1,"goods_price":obj.price ,total_price: price,"remarks": "","is_pack":0,"is_wait":0,"is_give":0,"is_old":0,"cookbook":localStorage.getItem("cookbook")};

		marry_fun(data);

		$(".guige").html("").removeClass("open");
		

	})
	
	//取消
	$(".guige-box .close1,.guige-box .bg").click(function(){
		$(".guige").html("").removeClass("open");
		$(".order-art-list .item-l").removeClass("opens")
	})
	$(".guige .guige-box .bg").on('touchmove', function (e) {e.preventDefault(); })
}

//分布点餐规格选择
var fenbu_vue="";//分布点餐vue全局
function addspec_buzhou(obj){
	var obj=obj,
		menuobj=JSON.parse(localStorage.getItem("key1")),
		specjson={};
		specjson["spec"]=caidan_json[obj.id].spec_list
		$.each(specjson["spec"], function(i,v) {
			v["goods_spec_name"]=guige1_json[v.spec_id].goods_spec_name
		});
		specjson["garnish"]=caidan_json[obj.id].garnish_list;
		$.each(specjson["garnish"], function(i,v) {
			v["goods_garnish_name"]=peicai_json[v.garnish_id].goods_garnish_name
		});
		specjson["taste"]=caidan_json[obj.id].taste_list;
		$.each(specjson["taste"], function(i,v) {
			v["goods_taste_name"]=kouwei1_json[v.taste_id].goods_taste_name
		});
		specjson["name"]=caidan_json[obj.id].goods_name
		specjson["info"]=caidan_json[obj.id];
		//设置原始单价
		//obj["price"]=caidan_json[obj.id].goods_price
		if(caidan_json[obj.id].goods_price_d){
			obj["price"]=caidan_json[obj.id].goods_price_d
		}else{
			obj["price"]=caidan_json[obj.id].goods_price
		}
		
		specjson["price"]=obj["price"]
		
		fenbu_vue.obj=specjson;
		fenbu_vue.start();
		console.log(specjson)
		
}



//弹出详情
$(document).on("click", ".menu-right .item .w img", function (e) {
	e.stopPropagation();
	e.preventDefault();
	
    $(".select_article").show().addClass("open");
    var id = $(this).parents(".item").attr("data-id"),
        parid = $(this).parents(".item").attr("data-parent-id"),
        num = $(this).parents(".item").find(".addright").attr("data-num");
    
    var newobj= JSON.parse(JSON.stringify(caidan_json[id]));
    newobj["num"] = num;
    newobj["oss"]= ossroot;
   // console.log(newobj)
    $("#article-w").html(template("article-js", newobj));
    setlange_obj()//设置前端语言

})
$(document).on("click", ".bg_mask,.select_article .close", function () {
    $(".select_article").hide().removeClass("open");
})


//弹出购物清单
var timeshow=setTimeout(function(){},0);
$(document).on("click", ".open #icon_gw,.mask,.open #xuanhaole,.carbuy .car-tit .back", function () {
	//if($(this).hasClass("null")) return false;
	$(".select-menu").toggleClass("open-gwc");
	
	if(!setjunli){
		 $.modal({
	        title: lange["1124"],
	        text: "<span class='c666'>"+lange["1200"]+"</span>",
	        buttons: [
	          { text: "OK", onClick: function () {}}
	         ]
	     });
	     $(".select-menu").removeClass("open-gwc");
	     return false;
	}
   
    if($(".select-menu").hasClass("open-gwc")){
    	$("#icon_gw").addClass("null");
    	var sts=getCookie("from")=="app"?24:0;
    	$(".car-box").css("max-height",$(window).height()-$(".carbuy .car-tit").outerHeight()-$(".select-buy").height()-sts)
    	
    	
    }else{
    	$("#icon_gw").removeClass("null")
    }
})

$(document).on('touchmove',".mask", function (e) {e.preventDefault(); })



//语言选择下拉框
function selectLanguage(call){
	var lan1={"set":getCookie("language"),"lan":setlanges}
        $("#lang-xiala").html(template("lang-xial-js", lan1));  
        $("#lang-xiala .l").text( $("#lang-xiala .on").text());
        $("#lang-xiala").on("click",function(e){
        	$(this).toggleClass("open");
        	var obj=$(e.target),
        		lan=obj.attr("data-lan")
        	if(lan){
        		obj.addClass("on").siblings().removeClass("on");
        		$("#lang-xiala .l").text(obj.text())
        		
        		setCookie("language", lan, 30);
    			setlane = getCookie("language");
    			
    			var tim111 = setInterval(function () {
			        $.showLoading();
			        clearInterval(tim111);
			    }, 500);
	        	$.ajax({ 
				  type:"get", 
				  timeout : 12000, 
				  url:'/language/'+ getCookie("language") +'.json?r='+Math.random(), 
				  dataType:"json", 
				  success:function(msg){ 
				  	clearInterval(tim111);
			        $.hideLoading();
			        
				   lange = typeof msg=="string"? JSON.parse(msg):msg;
		           setlange_obj(); 
		           if(call!=undefined)call();
		        	
				  },
			        error: function () {
			        	clearInterval(tim111);
			            $.hideLoading();
			        	
			            $.modal({
				          title: "tips",
				          text: "Loading timeout",
				          buttons: [
				            { text: "Refresh", onClick: function(){
				            	location.reload(true)   
				            } }
				          ]
				       });
			        }
				})
        		
        	}
        })			
        //
}


//断开后定时重连
function getrepartdata() {
    //重新载入已选数据
    try{
    	if(getCookie("from")=="APP"){
    		Q.go("main-html")
    	}else{
    		Q.go("root-html")
    	} 
    }catch(e){
    	//TODO handle the exception
    }
}

//消息提示
function msg1(text, dat) {
    var dt = dat || 3000;
    var obj = $("<div class='masg1'><span>" + text + "</span></div>");
    $("body").append(obj);
    setTimeout(function () { obj.addClass("open") }, 10)
    var ss = setTimeout(function () {
        obj.remove();
    }, dt)
}
//WebSocket
var ws;
var client_id;
var vartime;
function connect() {
	connect_b=false;	
    ws = new WebSocket(htpwss);
    // 服务端主动推送消息时会触发这里的onmessage
    ws.onmessage = function (e) {
        
        // json数据转换成js对象
        var data = eval("(" + e.data + ")");
        var type = data.type || '';
        
        if(data.time){
        	vartime=data.time      	 
        }
        
        if(setUI()){//判断是否为点餐界面
		        console.log(data)
		        switch (type) {
		        	case 'ping':
            		ws.send("{'type':'pong'}");
            		break;		        	
		        	
		            // Events.php中返回的init类型的消息，将client_id发给后台进行uid绑定
		            case 'init':
		                client_id = data.client_id;		                
		                vartime=data.time;
		                //console.log(e.data);
		                // 利用jquery发起ajax请求，将client_id发给后端进行uid绑定
		                setCookie("client_id",data.client_id,1);
		                global_ajax(jsonpath + "bind", { "client_id": data.client_id }, function (e) {
		                    //console.log(e);
		                    setCookie("bind",1,1);
		                })
		                break;
		            case 'put_shop_order_confirm':
		            	//下单
//		            	localStorage.setItem("pax",data.pax)
//		                delete cart_obj.my_list[data.member_id]
//						marry_fun();
		            break;
		            	 
		            case 'delete_cart':
		                //清空购物车
//		                if (data.member_id != getCookie("yingsoft_home_member_id")) {
//	                	if(cart_obj.my_list[getCookie("yingsoft_home_member_id")]){
//		               		if(cart_obj.my_list[getCookie("yingsoft_home_member_id")].length!=0){
//		               		   var ss= lange["1040"]
//		                	   $.modal({
//						          title: lange["1124"],
//						          text: ss,
//						          buttons: [
//						            { text: lange["1125"], onClick: function(){
//						            	if(data.type!="delete_cart"){
//						            		Q.go("root-html")
//						            	}
//						            } }
//						          ]
//						       });
//						    }
//	               		}
//		                }				
//						//重新载入已选数据
//		                try{
//		                	setselect_item();
//		                }catch(e){
//		                	//TODO handle the exception
//		                }
//		                //console.log(123123)
//		                $(".select-menu").removeClass("open-gwc");

                break;
            case 'put_cart'://点击选好了推送通知
//          	cart_obj.my_list[data.member_id]=data.data;
//          	console.log(cart_obj)
//				try{
//              	marry_fun();//更新模板
//              }catch(e){
//              	//TODO handle the exception
//              }
                break;
            case 'put_set_cart'://加减数量推送
//          	if (data.member_id != getCookie("yingsoft_home_member_id")) {
//	            	var nl=getindex(cart_obj.my_list[data.member_id],data.data.cart_id,'cart_id')
//	            	cart_obj.my_list[data.member_id][nl].count=data.data.count;
//	                try{
//	                	marry_fun();//更新模板
//	                }catch(e){
//	                	//TODO handle the exception
//	                }
//              }
                break;
             case 'put_set_cart'://更改打包状态
//          	if (data.member_id != getCookie("yingsoft_home_member_id")) {
//	            	var nl=getindex(cart_obj.my_list[data.member_id],data.data.cart_id,'cart_id')
//	            	cart_obj.my_list[data.member_id][nl].is_pack=data.data.is_pack;
//	                try{
//	                	marry_fun();//更新模板
//	                }catch(e){
//	                	//TODO handle the exception
//	                }
//              }
                break;
            case 'run_scan_code':
                //扫描进入通知
                msg1(lange["1038"])
                setCookie("other","1",1)
                break;		
            case 'put_order_confirm':
				//结账
				 //delCookie("yingsoft_home_encode");
				 delCookie("yingsoft_home_shop_encode");
				 Q.go('lose-html') 
				 break;
			case 'put_order_info_table':
				//换桌
				 Q.go('changing-html') 
				break;
                // 当mvc框架调用GatewayClient发消息时直接alert出来
            default:
                //console.log(e.data);
        }
    }
    };
    ws.onclose = function () {
        console.log("连接关闭，定时重连");
        connect();
    };
    ws.onerror = function () {
        console.log("出现错误");
    };
}//
//connect()



//地图定位
function setmap1(ss){
	var map;
	var watchId;
	var watchIdCount = 1;
	//alert("请求位置")
	
	if (navigator.geolocation) {
		//alert(JSON.stringify(navigator.geolocation))
	    watchId = navigator.geolocation.getCurrentPosition(showPosition, showError, {enableHighAcuracy: true, timeout: 5000, maximumAge:100000});
	    //设置定位缓存
	    return watchId;
	} else {
		if(ss!=2){
		    $.modal({
		        title: "tip",
		        text: "Device not supported！",
		        buttons: [
		          { text: "<span class='aaa'>ok</span>", onClick: function () {
		
		            }}
		        ]
		    });
	    }
	    return false;
	}
}

function showPosition(position) {
	
//  positioning.latitude = position.coords.latitude;//纬
//  positioning.longitude = position.coords.longitude;//经
//  positioning.accuracy = position.coords.accuracy;//精确度
	
	setCookie("gps",position.coords.latitude+","+position.coords.longitude,1)
	
	try{
    	setindexpage.start.success1();
    }catch(e){
    	// handle the exception
    }
	//?latlng=39.8998854032,116.6101441362&key=
	$(".position_p").text(lange[1188])
	$.ajax({
	 	type: "get",
        dataType: "json",
        url: "https://maps.googleapis.com/maps/api/geocode/json",
        data: {"latlng":position.coords.latitude+","+position.coords.longitude,"key":"AIzaSyD6y069KLRK7rnWuMikfibiV9VsH3HjsGg"},
        success: function (e) {
        	$(".position_p").text(e.results[0].address_components[0].long_name)
        }
    })
    return position
    
}
function showError(error) {
    var t_h = "错误信息：<br>";
    switch (error.code) {
        case error.TIMEOUT:
            t_h += "请求超时。如果在中国地区，谷歌 Chrome 或基于此内核的浏览器可能无法定位，您可以尝试其它浏览器如 IE / Edge。<br />A timeout occured! Please try again!";
            break;
        case error.POSITION_UNAVAILABLE:
            t_h += "抱谦，无法检测位置。如果设备有GPS，需在室外且GPS正常启动。<br />We can't detect your location. Sorry!";
            break;
        case error.PERMISSION_DENIED:
            t_h += "请充许浏览器访问地理位置请求。<br />Please allow geolocation access for this to work.";
            break;
        case error.UNKNOWN_ERROR:
            t_h += "发生未知错误<br />An unknown error occured!";
            break;
        default:
            t_h += "发生未知错误<br />An unknown error occured!";
            break;
    }
    console.log(t_h)
   // console.log(setindexpage.start.setintergps)
   //错误回调
    try{
    	setindexpage.start.error1();
    }catch(e){
    	// handle the exception
    }

//  $.modal({
//      title: "测试",
//      text: t_h,
//      buttons: [
//        { text: "<span class='aaa'>ok</span>", onClick: function () {
//
//          }}
//      ]
//  });
    
	return false;
    //失败
}
//计算两点间距离
function getGreatCircleDistance(lat1, lng1, lat2, lng2) {
    var EARTH_RADIUS = 6378137.0;//单位M
    var radLat1 = getRad(lat1);
    var radLat2 = getRad(lat2);
    var a = radLat1 - radLat2;
    var b = getRad(lng1) - getRad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000.0;
    console.log(s)
    return s;
}
//getGreatCircleDistance(1.5158274568447936,103.6682628840208,1.515804097509356,103.6682012627918)
//getGreatCircleDistance(1.5158274568447936,103.6682628840208,1.5157781,103.6681195)
//getGreatCircleDistance(1.5158274568447936,103.6682628840208,1.5157847,103.6680992)
function getRad(d) {
    var PI = Math.PI;
    return d * PI / 180.0;
}




var setwindow=function(w) {
	// 空函数
	function shield() {
		return false;
	}
	document.addEventListener('touchstart', shield, false); //取消浏览器的所有事件，使得active的样式在手机上正常生效
	document.oncontextmenu = shield; //屏蔽选择函数

	// H5 plus事件处理
	var ws = null,
		as = 'pop-in';
	var wgtVer = null;
	function plusReady() {
		ws = plus.webview.currentWebview();
//		plus.navigator.setStatusBarBackground("#222222"); //设置系统状态栏背景色
//		plus.navigator.setStatusBarStyle('#ffffff'); //设置系统状态栏字体颜色
		// Android处理返回键
		plus.key.addEventListener('backbutton', function() {
			if(android_bak){
				back();
			}			
		}, false);
	}
	if(w.plus) {
		plusReady();
	} else {
		document.addEventListener('plusready', plusReady, false);
	}


	// 处理返回事件
	w.back = function(hide) {
		if(w.plus) {
			ws || (ws = plus.webview.currentWebview());
			if(hide || ws.preate) {
				ws.hide('auto');
			} else {
				ws.close('auto');
			}
		} else if(history.length > 1) {
			history.back();
		} else {
			w.close();
		}
	};

	var openw = null,
		waiting = null;
	/**
	 * 打开新窗口
	 * @param {URIString} id : 要打开页面url
	 * @param {boolean} wa : 是否显示等待框
	 * @param {boolean} ns : 是否不自动显示
	 * @param {JSON} ws : Webview窗口属性
	 */
	w.clicked = function(id, wa, ns, ws) {
		if(openw) { //避免多次打开同一个页面
			return null;
		}		
		
		
		//判断登录状态			
		if(id.indexOf("?")==-1){
			id+="?"+root   //版本更新需要更改数字，清缓存
		}else{
			id+="&"+root   //版本更新需要更改数字，清缓存
		}
		
		if(w.plus) {
			wa && (waiting = plus.nativeUI.showWaiting());
			ws = ws || {};
			ws.scrollIndicator || (ws.scrollIndicator = 'none');
			ws.scalable || (ws.scalable = false);
			var pre = ''; //'http://192.168.1.178:8080/h5/';
			openw = plus.webview.create(pre + id, id, ws, {
				popGesture: 'close'
			});
			var sws=plus.nativeUI.showWaiting();
			ns || openw.addEventListener('loaded', function() { //页面加载完成后才显示
				//		setTimeout(function(){//延后显示可避免低端机上动画时白屏
				openw.show(as);
				sws.close();
			}, false);
			openw.addEventListener('close', function() { //页面关闭后可再次打开
				
				//
				openw = null;
			}, false);
			
		    
			return openw;
		} else {
			w.location.href=id;
		}
		return null;
	};

	/**
	 * 关闭等待框
	 */
	w.closeWaiting = function() {
		waiting && waiting.close();
		waiting = null;
	}

}
setwindow(window);




